# coding=utf-8
from flask import Blueprint,current_app,jsonify
from db.db_utils import MySQL
from models.aiModel import aiModel
from datetime import datetime
import time
import configparser
import sys

aicontroller = Blueprint('ai_controller',__name__)

"""
读取配置文件
"""
try:
    cf = configparser.ConfigParser()
    # cf.optionsxform = str  # 若出现不分大小写字符的情况 用这个
    cf.read('./conf/config.ini')
    domain = cf.get('web','domain')
except Exception as e:
    current_app.logger.debug('请确保config.ini是否存在,或配置不正确！')
    current_app.logger.debug(e)
    sys.exit(0)

@aicontroller.route('/api/jaitask', methods=['GET'])
async def process_items():
    with MySQL() as db:
        sql = "select tj.id,tj.user_id,tj.num,tj.type, \
                tjp.id as p_id,tjp.submit_id,tjp.ai,tjp.ai_report,tjp.content,tjp.ai_para,tjp.filepath,tjp.filename from fa_task_jai tj \
                left join fa_task_jai_process tjp \
                on tjp.id = (SELECT id FROM fa_task_jai_process WHERE jai_id = tj.id and status = 0 ORDER BY createtime DESC LIMIT 1) \
                where tj.del_flag = 0 and tj.status = 0"
        # 查询出所有可执行的任务
        res = db.query_all(sql)
        if not res:
            current_app.logger.debug("暂无任务")
            return jsonify({
                "status": "completed",
                "msg": "暂无任务"
            })
        """
        处理接口：接收要处理的item列表，异步调用第三方API并执行业务逻辑
        """
        try:
            # 开始流程
            current_app.logger.info(f"Starting to process {len(res)} items")
            start_time = datetime.now()
            aimodel = aiModel()
            # 处理文章格式
            textRes = aimodel.handle_text(res,db)
            # 异步调用，所有段落AI处理
            results = await aimodel.batch_handle_main_process(textRes)
        
            # 拼成新文章，新增子流程
            for i in results:
                resData = aimodel.transform_data(i)
                jai_id = resData['id']
                pid = resData['p_id']
                ai_para = resData['ai_para']
                user_id = resData['user_id']
                # 判断重复子流程
                p_res = db.query_all("select * from fa_task_jai_process where last_id = %s",(pid))
                if p_res:
                    continue
                current_app.logger.debug(f"================用户id:{user_id} 主流程id:{jai_id} 子流程id:{pid} 上传论文查重开始=================")
                wordRes = aimodel.create_word_document(resData['content'])
                current_app.logger.debug("生成docx返回:")
                current_app.logger.debug(wordRes)
                if not wordRes:
                    current_app.logger.debug("docx文件生成异常")
                    continue
                filepath = wordRes['filepath']
                filename = wordRes['filename']
                uploadRes = aimodel.uploadApi(filepath)
                if 'error' in uploadRes:
                    current_app.logger.debug("上传查重API异常")
                    continue
                dataid = uploadRes['data']['data_id']
                taskid = uploadRes['data']['uid']
                file_url = domain + '/' + filepath.replace("\\","/")
                db.execute_many_sqls([
                    ("UPDATE fa_task_jai_process SET status = 1,updatetime = %s WHERE id = %s", 
                     (time.time(), pid)),
                    ("INSERT INTO fa_task_jai_process(jai_id, submit_id,task_id, filename, filepath,file_url,content,ai_para,last_id,createtime) VALUES (%s, %s, %s, %s, %s,%s,%s, %s, %s, %s)",
                    (jai_id, dataid,taskid, filename, filepath,file_url,resData['content'],','.join(map(str,ai_para)),pid,time.time())),
                    ("UPDATE fa_task_jai SET num = num + 1,updatetime = %s WHERE id = %s", 
                     (time.time(), jai_id)),
                ])
                current_app.logger.debug(f"================用户id:{user_id} 主流程id:{jai_id} 子流程id:{pid} 上传论文查重结束=================")
            # 计算处理时间
            processing_time = (datetime.now() - start_time).total_seconds()
            current_app.logger.info(f"Completed processing in {processing_time:.2f} seconds")
            
            # 返回处理结果
            return jsonify({
                "status": "completed",
                "processing_time_seconds": processing_time,
                "total_items": len(results),
                "success_count": len([r for r in results if 'error' not in r]),
                "failed_count": len([r for r in results if 'error' in r]),
                "results": results
            })
        except Exception as e:
            current_app.logger.error(f"Error in processing: {str(e)}")
            return jsonify({"error": str(e)}), 500

